package com.alameda.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 文本工具类
 *
 * @author Lv
 * @date 2024/6/16
 */
public class TextUtils {
    /**
     * 下载txt文件
     *
     * @param content             文件内容
     * @param httpServletResponse http响应对象
     */
    public static void downloadText(String content, HttpServletResponse httpServletResponse) {
        downloadText(content, "example", httpServletResponse);
    }

    /**
     * 下载txt文件
     *
     * @param content             文件内容
     * @param fileName            文件名称
     * @param httpServletResponse http响应对象
     */
    public static void downloadText(String content, String fileName, HttpServletResponse httpServletResponse) {
        // 设定文件名称
        String exportFileName = "";
        try {
            exportFileName = URLEncoder.encode(fileName + ".txt", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 设置响应的内容类型和字符集
        httpServletResponse.setContentType("text/plain;charset=utf-8");
        // 设置响应的头信息
        httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + exportFileName);
        // 写入响应
        PrintWriter writer = null;
        try {
            writer = httpServletResponse.getWriter();
            // 写入TXT文件的内容
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            assert writer != null;
            writer.close();
        }
    }
}
